package com.qq.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.qq.bean.Dynamics;
import com.qq.bean.LikeDynamics;
//import com.qq.bean.Users;
import com.qq.dao.BaseDao;
import com.qq.dao.LikeDynamicsDao;

public class LikeDynamicsDaoImpl implements LikeDynamicsDao {

	@Override
	public int insertLikeDy(LikeDynamics likedy) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		String sql = "INSERT IGNORE INTO likedy(dynamics_id,user_id,like_time,state) VALUES (?,?,NOW(),1)";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, likedy.getDynamicsId());
			ps.setInt(2, likedy.getUserId());
			result = ps.executeUpdate();
		} catch (SQLException e) {
			
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, null);
		}
		return result;
	}

	@Override
	public int deletLikeDy(int dynamics_id, int user_id) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		String sql = "DELETE FROM likedy WHERE dynamics_id = ? AND user_id = ?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1,dynamics_id);
			ps.setInt(2, user_id);
			result = ps.executeUpdate();
		} catch (SQLException e) {			
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, null);
		}
		
		return result;
	}

	@Override
	public List<String> selectLikedyNickName(int dynamics_id) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		List<String> nicknames = new ArrayList();
		String sql = "SELECT u.nickName FROM likedy l JOIN `users` u ON l.user_id = u.userId WHERE dynamics_id = ?";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, dynamics_id);
			//System.out.println(ps);
			res = ps.executeQuery();
			while(res.next()) {
				String nickName = res.getString("nickName"); // 或 rs.getString("u.nickName")
		        nicknames.add(nickName);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}
		
		return nicknames;
	}

	@Override
	public int SelectLikeCount(int dynamics_id) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		int rows = 0;
		String sql = "SELECT COUNT(1) as likeNum FROM likedy WHERE dynamics_id = ? ";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, dynamics_id);
			//System.out.println(ps);
			res = ps.executeQuery();
			if(res.next()) {
				rows = res.getInt("likeNum");
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}
		
		return rows;
	}


}
